<template>
  <div class="store-orders-page">
    <a-card title="门店订单管理" :bordered="false">
      <!-- 搜索和筛选区域 -->
      <div class="table-operations">
        <a-space>
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索订单号"
            style="width: 200px"
            @search="onSearch"
          />
          <a-select
            v-model:value="statusFilter"
            style="width: 120px"
            placeholder="订单状态"
            @change="onStatusChange"
          >
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option value="0">待支付</a-select-option>
            <a-select-option value="1">已支付</a-select-option>
            <a-select-option value="2">制作中</a-select-option>
            <a-select-option value="3">已完成</a-select-option>
            <a-select-option value="4">已取消</a-select-option>
          </a-select>
          <a-range-picker
            v-model:value="dateRange"
            style="width: 240px"
            @change="onDateChange"
          />
        </a-space>
      </div>

      <!-- 订单列表 -->
      <a-table
        :columns="columns"
        :data-source="orders"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="orderId"
      >
        <!-- 订单号列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orderId'">
            <span>{{ record.orderId }}</span>
          </template>

          <!-- 订单状态列 -->
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <!-- 订单金额列 -->
          <template v-if="column.key === 'totalPrice'">
            <span class="price">¥{{ record.totalPrice }}</span>
          </template>

          <!-- 操作列 -->
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="showOrderDetail(record)">
                查看详情
              </a-button>
              <a-button 
                v-if="record.status === 0" 
                type="link" 
                @click="handlePay(record)"
              >
                确认支付
              </a-button>
              <a-button 
                v-if="record.status === 1" 
                type="link" 
                @click="handleStartMaking(record)"
              >
                开始制作
              </a-button>
              <a-button 
                v-if="record.status === 2" 
                type="link" 
                @click="handleComplete(record)"
              >
                完成订单
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 订单详情弹窗 -->
      <a-modal
        v-model:visible="detailModalVisible"
        title="订单详情"
        width="800px"
        :footer="null"
      >
        <template v-if="currentOrder">
          <a-descriptions bordered>
            <a-descriptions-item label="订单号" :span="3">
              {{ currentOrder.orderId }}
            </a-descriptions-item>
            <a-descriptions-item label="订单状态" :span="3">
              <a-tag :color="getStatusColor(currentOrder.status)">
                {{ getStatusText(currentOrder.status) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="下单时间" :span="3">
              {{ formatDate(currentOrder.createTime) }}
            </a-descriptions-item>
            <a-descriptions-item label="订单金额" :span="3">
              <span class="price">¥{{ currentOrder.totalPrice }}</span>
            </a-descriptions-item>
          </a-descriptions>

          <div class="order-items">
            <h3>商品列表</h3>
            <a-table
              :columns="itemColumns"
              :data-source="currentOrder.orderItemList"
              :pagination="false"
              row-key="productId"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'image'">
                  <img :src="record.imageUrlList[0]" :alt="record.name" class="product-image">
                </template>
                <template v-if="column.key === 'price'">
                  <span class="price">¥{{ record.price }}</span>
                </template>
              </template>
            </a-table>
          </div>
        </template>
      </a-modal>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import type { TablePaginationConfig } from 'ant-design-vue';
import { listOrder, pay, startMaking, complete } from '@/api/order';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    title: '订单号',
    dataIndex: 'orderId',
    key: 'orderId',
    width: 180,
  },
  {
    title: '订单状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
  },
  {
    title: '下单时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    sorter: true,
  },
  {
    title: '订单金额',
    dataIndex: 'totalPrice',
    key: 'totalPrice',
    width: 120,
    sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 200,
  },
];

// 商品列表列定义
const itemColumns = [
  {
    title: '商品图片',
    dataIndex: 'image',
    key: 'image',
    width: 100,
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '规格',
    dataIndex: 'paramList',
    key: 'paramList',
    customRender: ({ text }) => text?.map((param: any) => param.paramValueName).join(', ') || '-',
  },
  {
    title: '单价',
    dataIndex: 'price',
    key: 'price',
    width: 100,
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    key: 'quantity',
    width: 100,
  },
];

// 状态和数据
const loading = ref(false);
const orders = ref<any[]>([]);
const searchText = ref('');
const statusFilter = ref('');
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | null>(null);
const detailModalVisible = ref(false);
const currentOrder = ref<any>(null);

// 分页配置
const pagination = reactive<TablePaginationConfig>({
  total: 0,
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
});

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      orderId: searchText.value,
      status: statusFilter.value,
      startTime: dateRange.value?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
      endTime: dateRange.value?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
    };

    const res = await listOrder(params);
    if (res.data.code === 200) {
      orders.value = res.data.data.list;
      pagination.total = res.data.data.total;
    } else {
      message.error(res.data.msg || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    message.error('获取订单列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 获取状态颜色
const getStatusColor = (status: number) => {
  const colorMap: Record<number, string> = {
    0: 'processing',
    1: 'success',
    2: 'warning',
    3: 'success',
    4: 'error'
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '待支付',
    1: '已支付',
    2: '制作中',
    3: '已完成',
    4: '已取消'
  };
  return textMap[status] || '未知状态';
};

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 搜索处理
const onSearch = () => {
  pagination.current = 1;
  fetchOrders();
};

// 状态筛选处理
const onStatusChange = () => {
  pagination.current = 1;
  fetchOrders();
};

// 日期筛选处理
const onDateChange = () => {
  pagination.current = 1;
  fetchOrders();
};

// 表格变化处理
const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.current = pag.current || 1;
  pagination.pageSize = pag.pageSize || 10;
  fetchOrders();
};

// 显示订单详情
const showOrderDetail = (record: any) => {
  currentOrder.value = record;
  detailModalVisible.value = true;
};

// 处理支付
const handlePay = async (record: any) => {
  try {
    const res = await pay(record.orderId);
    if (res.data.code === 200) {
      message.success('支付成功');
      fetchOrders();
    } else {
      message.error(res.data.msg || '支付失败');
    }
  } catch (error) {
    console.error('支付失败:', error);
    message.error('支付失败，请稍后重试');
  }
};

// 处理开始制作
const handleStartMaking = async (record: any) => {
  try {
    const res = await startMaking(record.orderId);
    if (res.data.code === 200) {
      message.success('已开始制作');
      fetchOrders();
    } else {
      message.error(res.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('操作失败:', error);
    message.error('操作失败，请稍后重试');
  }
};

// 处理完成订单
const handleComplete = async (record: any) => {
  try {
    const res = await complete(record.orderId);
    if (res.data.code === 200) {
      message.success('订单已完成');
      fetchOrders();
    } else {
      message.error(res.data.msg || '操作失败');
    }
  } catch (error) {
    console.error('操作失败:', error);
    message.error('操作失败，请稍后重试');
  }
};

// 初始化
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.store-orders-page {
  padding: 24px;
}

.table-operations {
  margin-bottom: 16px;
}

.price {
  color: #f5222d;
  font-weight: 500;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.order-items {
  margin-top: 24px;
}

.order-items h3 {
  margin-bottom: 16px;
  font-weight: 500;
}
</style> 